package me.evis.gae.guestbook.sever;

import java.text.DateFormat;
import java.util.Date;
import java.util.List;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import me.evis.gae.guestbook.bo.Comment;
import me.evis.gae.guestbook.bo.dao.CommentDao;
import me.evis.gae.guestbook.client.CommentService;

@SuppressWarnings("serial")
public class CommentServiceImp extends RemoteServiceServlet 
    implements CommentService {
    
	@Override
    public String addComment(String name, String comment) {
        Comment newComment = new Comment();
        newComment.setUsername(name);
        newComment.setComment(comment);
        newComment.setCreateDate(new Date(System.currentTimeMillis()));

        Comment storedComment = CommentDao.create(newComment);
        String result;
        if (storedComment != null) {
            result = "New comment has been added with ID: "
                         + storedComment.getId() + ".";
        } else {
            result = "Failed to add comment.";
        }
        return result;
    }
    
    @Override
    public String listComment() {
        List<Comment> comments = CommentDao.retrieve();
        StringBuffer result = new StringBuffer();
        result.append("<ul>");
        for (Comment comment : comments) {
            result.append("<li id=\"")
                  .append(comment.getId())
                  .append("\"><span class=\"username\">")
                  .append(comment.getUsername())
                  .append("</span> said on ")
                  .append("<span class=\"commentDate\">")
                  .append(DateFormat.getDateTimeInstance()
                                    .format(comment.getCreateDate()))
                  .append("</span><p class=\"comment\">")
                  .append(comment.getComment())
                  .append("</p></li>");
        }
        result.append("</ul>");
        return result.toString();
    }

}
